package com.ht.medicaltreatment.activity

import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ClickUtils
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.SampleAddAdapter2
import com.ht.medicaltreatment.bean.RfidSample
import com.ht.medicaltreatment.utils.ScanUtils
import com.ht.medicaltreatment.utils.SoundUtils
import com.ht.medicaltreatment.view.UserNameDialog
import com.ht.medicaltreatment.viewmodel.SampleReturnScanViewModel
import com.ht.medicaltreatment.viewmodel.SampleScanViewModel
import com.xgst.lib.utils.TimeUtils
import com.xgst.lib.utils.showToast
import kotlinx.android.synthetic.main.activity_inventory.*
import kotlinx.android.synthetic.main.activity_sample_return_scan_layout.*

/**
 * 通过扫描的方式存入冰箱
 */
class SampleScanReturnActivity : BaseActivity(), View.OnClickListener, OnItemClickListener {
    override fun getLayoutId() = R.layout.activity_sample_return_scan_layout

    private val model by viewModels<SampleReturnScanViewModel>()
    private var itemAllCount = 0
    private var itemCheckCount = 0
    private var scanCount = 0
    private val adapter = SampleAddAdapter2()
    private var isOpen = false
    private val list = mutableListOf<String>()
    private var remarks = ""
    private var returnPerson = ""
    private var returnTableName = ""
    private var userDialog: UserNameDialog? = null

    override fun init() {
        setTitle("识别存入冰箱")
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter

        ScanUtils.init(onInitResult = {
            btnStart.setBackgroundColor(getColor(R.color.blue))
            btnStart.isEnabled = true
        })

        adapter.setOnItemClickListener(this)
        btnStart.setOnClickListener(this)
        cbAll.setOnClickListener(this)
        btnPositive.setOnClickListener(this)
        llTop.setOnClickListener(this)

        ClickUtils.expandClickArea(cbAll,70)
    }

    override fun onClick(v: View?) {
        when(v){
            btnStart -> {
                if(isOpen){
                    ScanUtils.close()
                    isOpen = false
                    btnStart.text = "开始扫描"
                    btnStart.setBackgroundColor(resources.getColor(R.color.blue))
                    if(list.size == 0){
                        return
                    }
                    showProgress()
                    var ids:String? = null
                    list.forEach {
                        if(ids == null){
                            ids = "$it"
                        }else{
                            ids = "$ids,$it"
                        }
                    }

                    model.scanOfRfid(ids!!,{
                        dismissProgress()
                        if(it != null){
                            itemAllCount = it.size
                        }
                        adapter.setNewInstance(it)
                    },{
                        dismissProgress()
                        showToast(it)
                    })
                }else{
                    isOpen = true
                    scanCount = 0
                    btnStart.text = "停止扫描"
                    btnStart.setBackgroundColor(resources.getColor(R.color.color99))
                    ScanUtils.open {
                        SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
                        list.add(it)
                        scanCount++
                        tvScanCount.text = "$scanCount"
                    }
                }
            }

            cbAll -> {
                if(cbAll.isChecked){
                    adapter.data.forEach {
                        it.isCheck = true
                    }
                    itemCheckCount = itemAllCount
                }else{
                    adapter.data.forEach {
                        it.isCheck = false
                    }
                    itemCheckCount = 0
                }
                tvCheckCount.text = "$itemCheckCount"
                adapter.notifyDataSetChanged()
            }

            //归还人
            llTop -> {
                if(userDialog == null){
                    userDialog = UserNameDialog(this)
                }
                userDialog!!.show { account, psw ->
                    model.getUserName(account, psw) {
                        tvReturnName.text = it
                    }
                }
            }

            btnPositive -> {
                if(itemCheckCount == 0){
                    showToast("请选择")
                    return
                }
                if (tvReturnName.text.isEmpty()) {
                    showToast("请输入归还人姓名")
                    return
                }
                returnPerson = tvReturnName.text.toString()
                remarks = etRemark.text.toString()
                returnTableName = "临床试验进入冰箱(归还)记录${TimeUtils.getCurrentTime("yyyyMMddHHmmss")}"

                showProgress()
                var ids = ""
                adapter.data.forEach {
                    if(it.isCheck){
                        if(ids.isEmpty()){
                            ids = "${it.id}"
                        }else{
                            ids = "$ids,${it.id}"
                        }
                    }
                }
                LogUtils.i(returnPerson,remarks,ids,returnTableName)
                model.returnRefrigerator(returnPerson, remarks, ids, returnTableName, {
                    dismissProgress()
                    showToast("归还成功")
                    finish()
                }, {
                    dismissProgress()
                    showToast(it)
                })
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ScanUtils.close()
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = adapter.data[position] as RfidSample
        if(item.isCheck){
            item.isCheck = false
            if(cbAll.isChecked){
                cbAll.isChecked = false
            }
            itemCheckCount--
        }else{
            item.isCheck = true
            itemCheckCount++
            if(itemCheckCount == itemAllCount){
                cbAll.isChecked = true
            }
        }
        tvCheckCount.text = "$itemCheckCount"
        adapter.notifyItemChanged(position)
    }
}
